package main.java.com.epam;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class RingBuffer {

	private int size;
	private int currentPos;
	private List<String> data;

	private final Lock lock = new ReentrantLock();
	private final Condition notFull  = lock.newCondition();
	private final Condition notEmpty = lock.newCondition();

	public RingBuffer(int size){
		this.size = size;
		data = new LinkedList<String>();
	}

	public  void insertMessage(String message) throws InterruptedException {
		lock.lock();
		try {
			while (isFull()){notFull.await();}
			data.add(currentPos++, message);
			notEmpty.signalAll();
		} finally {
			lock.unlock();
		}
	}

	public String getMessage() throws InterruptedException  {
		lock.lock();
		try {
			while (isEmpty()) {notEmpty.await();}
			notFull.signalAll();
			return data.get(--currentPos);
		} finally {
			lock.unlock();
		}
	}

	public boolean isEmpty(){
		return currentPos <= 0;
	}

	public boolean isFull(){
		return currentPos >= size;
	}
	
	public List<String> getData(){
		return data;
	}

}
